import Vue from 'vue'
import VueRouter from 'vue-router'

/* 实现路由懒加载 */
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import User from '../components/user/User.vue'
import Rights from '../components/rights/Rights.vue'
import Role from '../components/rights/Role.vue'
import ItemCat from '../components/items/ItemCat.vue'
import ItemCatParam from '../components/items/ItemCatParam.vue'
import Item from '../components/items/Item.vue'
import AddItem from '../components/items/addItem.vue'
import Report from '../components/report/Report.vue'



Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [{
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/user',
        component: User
      },
      {
        path: '/rights',
        component: Rights
      },
      {
        path: '/role',
        component: Role
      },
      {
        path: '/itemCat',
        component: ItemCat
      },
      {
        path: '/itemCatParam',
        component: ItemCatParam
      },
      {
        path: '/item',
        component: Item
      },
      {
        path: '/item/addItem',
        component: AddItem
      },
      {
        path: '/report',
        component: Report
      }

    ]
  }
]

const router = new VueRouter({
  routes
})

//添加路由导航守卫, 如果已经登陆则 放行,如果没有登陆则跳转到登陆页面
//参数说明  to代表要跳转的路径   from 表示从哪个路径跳转回来   next表示放行  next('/login') 表示登陆
router.beforeEach((to, from, next) => {
  //判断是否为登陆页
  if (to.path === '/login') return next()
  //如果不是登陆页 则判断是否有token
  let token = window.sessionStorage.getItem('token')
  //如果不存在,则跳转到登陆页面
  if (!token) return next('/login')
  //如果存在,则跳转到指定页面
  next()
})

export default router
